package cn.buk.qms.web;

import cn.buk.common.JsonResult;
import cn.buk.qms.service.EnterpriseService;
import cn.buk.tms.exception.BaseException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;

@RestControllerAdvice
public class GlobalExceptionHandler extends BaseController {
  private static final Logger logger = LogManager.getLogger(GlobalExceptionHandler.class);

  @Autowired
  private EnterpriseService enterpriseService;

  /**
   * 接口参数校验异常
   */
  @ExceptionHandler(value = {Exception.class})
  public JsonResult handleGlobalException(HttpServletRequest request, Exception ex) {
    logger.error(ex.getMessage());
    ex.printStackTrace();

    enterpriseService.sendAlertMessage(getEnterpriseId(request), getUsername(request) + ": " + ex.getMessage());
    return JsonResult.createJsonResult(-1, ex.getMessage());
  }

  /**
   * 接口参数校验异常
   */
  @ExceptionHandler(value = {IOException.class})
  public JsonResult handleGlobalException(HttpServletRequest request, IOException ex) {
    ex.printStackTrace();
    return JsonResult.createJsonResult(-1, ex.getMessage());
  }

  /**
   * 接口参数校验异常
   */
  @ExceptionHandler(value = {BaseException.class})
  public JsonResult handleGlobalBaseException(HttpServletRequest request, BaseException ex) {
    logger.error(ex.getMessage());
    ex.printStackTrace();
    return JsonResult.createJsonResult(-ex.getErrcode(), ex.getMessage());
  }
}

